<template>
  <!-- 添加或修改设备对话框 -->
  <el-drawer
    :wrapperClosable="false"
    :size="'800px'"
    :title="title"
    :visible.sync="open"
    append-to-body
  >
    <el-container>
      <el-main>
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="top"
          label-width="80px"
        >
          <!-- 设备名称 -->
          <el-form-item label="告警名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入告警名称"/>
          </el-form-item>
          <!--触发条件-->
          <el-container>
            <!-- label="触发条件"-->
            <el-form-item>
              <div style="margin-bottom: 10px">
                {{'触发条件：'}}
                <el-switch
                  style="margin-left: 100px"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  inactive-text="是否开启防抖"
                  v-model="form.alarmRule.shakeLimit.enabled"/>
                <el-tooltip style="margin-left: 10px" placement="top">
                  <div slot="content" class="rule-box">
                    防抖默认时间单位为秒
                  </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
              </div>
              <div style="margin-bottom: 10px">
                <el-input v-if="form.alarmRule.shakeLimit.enabled" v-model="form.alarmRule.shakeLimit.time" class="cron"
                          placeholder="触发时长"/>
                <el-input v-if="form.alarmRule.shakeLimit.enabled" v-model="form.alarmRule.shakeLimit.threshold"
                          class="cron" placeholder="触发次数"/>
              </div>
              <el-row v-for="(v, i) in form.alarmRule.triggers" style="background-color:#F2F6FC">
                <div style="margin-top: 15px">
                  <el-select class="cron" v-model="v.trigger" placeholder="请选择触发类型">
                    <el-option
                      v-for="item in dict.type.alarm_trigger_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-input v-if="v.trigger === 'timer'" v-model="v.cron" class="cron" placeholder="cron表达式"/>
                  <el-button icon="el-icon-delete" style="margin-left: 10px" @click="removeAlarmTriggers(i)" circle/>
                </div>
                <div style="margin-top: 10px">
                  <el-select v-if="v.trigger === 'timer'" class="cron" v-model="v.type" placeholder="选择类型：如事件|属性">
                    <el-option
                      v-for="item in ModelType1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-select v-if="v.trigger === 'device'" class="cron" v-model="v.type" placeholder="选择类型：如事件|属性">
                    <el-option
                      v-for="item in ModelType2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-select v-if="v.type === 'event'" class="cron" v-model="v.modelId" placeholder="选择事件">
                    <el-option
                      v-for="item in deriveMetadata.events"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                  <el-select v-if="v.type === 'properties'" class="cron" v-model="v.modelId" placeholder="选择属性">
                    <el-option
                      v-for="item in deriveMetadata.properties"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                </div>
                <div style="margin-top: 10px" v-if="v.trigger !== null">
                  <el-row v-for="(v1, i1) in v.filters" style="margin-bottom: 10px">
                    <el-input v-model="v1.key" class="cron" placeholder="过滤条件KEY"/>
                    <el-select v-model="v1.operator" class="cron" placeholder="运算符">
                      <el-option
                        v-for="item in dict.type.alarm_operator"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                    <el-input v-model="v1.value" class="cron" placeholder="过滤条件值"/>
                    <el-button type="text" icon="el-icon-remove-outline" style="margin-left: 10px;margin-right: 10px" @click="removeAlarmFilters(i,i1)"/>
                  </el-row>
                  <el-button
                  style="margin-left: 10px"
                  type="text"
                  size="1"
                  icon="el-icon-circle-plus-outline"
                  v-hasPermi="['iot:product:save']"
                  @click="addAlarmFilters(i)"/>
                </div>
              </el-row>
              <el-button
                type="text"
                size="1"
                icon="el-icon-plus"
                v-hasPermi="['iot:product:save']"
                @click="addAlarmTriggers()"
              >
                新增触发条件
              </el-button>
            </el-form-item>
          </el-container>
          <!--转换-->
          <el-container>
            <el-form-item label="转换">
              <el-row v-for="(v, i) in form.alarmRule.properties"  style="background-color:#F2F6FC;margin-bottom: 10px">
                <el-input v-model="v.property" style="width: 220px;margin-left: 10px;margin-top: 10px;margin-bottom: 10px;" placeholder="属性"/>
                <el-input v-model="v.alias" class="cron" placeholder="别名"/>
                <el-button icon="el-icon-delete" style="margin-left: 10px;margin-right: 10px" @click="removeAlarmTransition(i)" circle/>
              </el-row>
              <el-button
                type="text"
                size="1"
                icon="el-icon-plus"
                v-hasPermi="['iot:product:save']"
                @click="addAlarmTransition()"
              >
                新增转换
              </el-button>
              <el-tooltip style="margin-left: 10px" placement="top">
                <div slot="content" class="rule-box">
                  将内置的结果字段转换为自定义字段,<br>
                  例如：deviceId 转为 id
                </div>
                <i class="el-icon-question"/>
              </el-tooltip>
            </el-form-item>
          </el-container>
          <!--执行操作-->
          <el-container>
            <el-form-item label="执行操作">
              <el-row v-for="(v, i) in form.alarmRule.actions"  style="background-color:#F2F6FC">
                <div style="margin-top: 10px">
                  <el-select v-model="v.executor" style="margin-left: 10px;margin-right: 10px" @change='emptyAction(i)' placeholder="请选择动作类型">
                    <el-option
                      v-for="item in dict.type.type_of_action"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-select v-if="v.executor === 'device-message-sender'"  v-model="v.configuration.deviceId"
                             style="margin-left: 10px;margin-right: 10px" placeholder="请选择设备">
                    <el-option
                      v-for="item in deviceList"
                      :key="item.id"
                      :label="item.deviceName"
                      :value="item.id"/>
                  </el-select>
                  <el-select v-if="v.configuration.deviceId !== undefined" @change='queryPropertyOrFunctionlList(v.configuration)' v-model="v.configuration.message.messageType" style="margin-left: 10px;margin-right: 10px"
                             placeholder="请选择类型 如属性|功能">
                    <el-option
                      v-for="item in objectModelType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </div>
                <div style="margin-top: 10px">
                  <el-select v-if="v.configuration.message.messageType === 'WRITE_PROPERTY'" v-model="v.configuration.message.propertyId" style="margin-left: 10px;margin-right: 10px"
                             placeholder="物模型属性">
                    <el-option
                      v-for="item in propertylList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                  <el-select v-if="v.configuration.message.messageType === 'INVOKE_FUNCTION'" v-model="v.configuration.message.functionId"
                             style="margin-left: 10px;margin-right: 10px" placeholder="物模型功能">
                    <el-option
                      v-for="item in functionlList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                  <el-select v-if="v.executor === 'notifier'" @change='queryNotifyConfigList(v.configuration)' v-model="v.configuration.notifyType" style="margin-left: 10px;margin-right: 10px"
                             placeholder="通知类型">
                    <el-option
                      v-for="item in dict.type.notify_config_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <el-select v-if="v.configuration.notifyType !== undefined" @change='queryNotifyTemplateList(v.configuration)' v-model="v.configuration.notifierId" style="margin-left: 10px;margin-right: 10px"
                             placeholder="选择通知配置">
                    <el-option
                      v-for="item in notifyConfigList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                  <el-select v-if="v.configuration.notifierId !== undefined" v-model="v.configuration.templateId" style="margin-left: 10px"
                             placeholder="选择通知模板">
                    <el-option
                      v-for="item in notifyTemplateList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                  <el-input v-if="v.configuration.message.propertyId !== undefined && v.configuration.message.messageType === 'WRITE_PROPERTY'" v-model="v.configuration.properties2" class="cron" placeholder="填写属性值"/>
                </div>
                <div style="margin-top: 10px">
                  <el-row v-for="(v1, i1) in functionlList">
                    <el-row v-if="v.configuration.message.functionId ===v1.id" v-for="(v2, i2) in v1.inputs">
                      <div v-if="v2.valueType.type !=='boolean'">
                        <el-input style="width: 220px;margin-left: 10px" v-model="v2.name+'('+v2.id+')'" :disabled="true"/>
                        <el-input style="width: 220px;margin-left: 10px" v-model="v2.value" placeholder="填写属性值"/>
                      </div>
                      <div v-if="v2.valueType.type === 'boolean'">
                        <el-form-item>
                          <el-input style="width: 220px;margin-left: 10px;margin-right: 10px" v-model="v2.name+'('+v2.id+')'" :disabled="true"/>
                          <template>
                            <el-radio v-model="v2.value" :label="v2.valueType.trueValue">{{v2.valueType.trueText}}</el-radio>
                            <el-radio v-model="v2.value" :label="v2.valueType.falseValue">{{v2.valueType.falseText}}</el-radio>
                          </template>
                        </el-form-item>
                      </div>
                    </el-row>
                  </el-row>
                </div>
                <el-button icon="el-icon-delete" style="margin-left: 10px;margin-right: 10px;margin-bottom: 10px;margin-top: 10px" @click="removeAlarmActions(i)" circle/>
              </el-row>
              <el-button
                type="text"
                size="1"
                icon="el-icon-plus"
                v-hasPermi="['iot:product:save']"
                @click="addAlarmActions()"
              >
                新增执行操作
              </el-button>
            </el-form-item>
          </el-container>
        </el-form>
      </el-main>
      <el-footer>
        <div class="bottom-bar" style="text-align: right">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-footer>
    </el-container>
  </el-drawer>
</template>

<script>
  import { mapState } from 'vuex'
  import {addDevice, getDevice, updateDevice, queryDevice} from '@/api/iot/device'
  import {getProduct} from '@/api/iot/product'
  import {queryConfig} from '@/api/notify/config'
  import {queryTemplate} from '@/api/notify/template'

  export default {
    name: "AlarmRecordingAddEdit",
    // 字典
    dicts: [
      "alarm_trigger_type",
      "alarm_operator",
      "type_of_action",
      "notify_config_type",
    ],
    computed: {
      ...mapState({
        // 设备数据
        deviceDetailInfo: state => state.device.deviceDetailInfo,
      }),
    },
    data() {
      return {
        //物模型对象
        deriveMetadata: {},
        //通知类型集合
        notificationList: [],
        //通知配置集合
        notifyConfigList:[],
        //通知模板集合
        notifyTemplateList:[],
        //物模型属性集合
        propertylList: [],
        //物模型功能集合
        functionlList: [],
        //执行动作中选择类型 如属性|功能
        objectModelType: [
            {
          value: 'WRITE_PROPERTY',
          label: '设置属性'
        }, {
          value: 'INVOKE_FUNCTION',
          label: '调用功能'
        }
        ],
        //触发类型为定时触发时
        ModelType1: [
        {
          value: 'properties',
          label: '属性'
        }, {
          value: 'event',
          label: '事件'
        }
        ],
        //触发类型为设备触发时
        ModelType2: [
            {
          value: 'properties',
          label: '属性'
        }, {
          value: 'event',
          label: '事件'
        }, {
          value: 'online',
          label: '上线'
        }, {
          value: 'offline',
          label: '下线'
        }
        ],
        //判断需要发的请求是新增还是修改
        type: null,
        //设备列表
        deviceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          publishState: null,
        },
        // 表单参数
        form: {
          //告警ID
          id: "1619503894379999232",
          //告警所属类型 产品、设备 此处为设备
          target: "device",
          //此告警所属的设备ID
          targetId: "yanshi001",
          //告警名称
          name: "告警名称",
          //告警详细信息
          alarmRule: {
            //此告警所属设备的ID
            name: "闸机产品G-001",
            //此告警设置所属设备的产品ID
            productId: "yanshi",
            //此告警设置所属设备的产品名称
            productName: "闸机产品G-001",
            //此告警设置的设备ID
            deviceId: "yanshi001",
            //此告警设置的设备名称
            deviceName: "闸机产品G-001",
            //触发条件
            triggers: [
              //第一个触发条件
              {
                //触发器类型 设备触发、定时触发 此处为设备触发
                trigger: "device",
                //类型：书简、属性、上线、下线 此处为上线
                type: "online",
                //条件集合
                filters: [
                  {
                    //KEY条件
                    key: "KEY",
                    //条件属性值
                    value: "设备触发条件值",
                    //操作符
                    operator: "eq"
                  }
                ]
              },
              //第二个触发条件
              {
                //触发器类型 设备触发、定时触发 此处为定时触发
                trigger: "timer",
                //cron公式
                cron: "定时触发",
                //类型：属性、功能 此处为属性
                type: "properties",
                //模型ID
                modelId: "test",
                //条件集合
                filters: [
                  {
                    //KEY条件
                    key: "test",
                    //条件属性值
                    value: "定时条件值",
                    //操作符
                    operator: "eq"
                  }
                ]
              }
            ],
            //转换
            properties: [
              {
                property: "属性1",
                alias: "别名1"
              },
              {
                property: "属性2",
                alias: "别名2"
              }
            ],
            //执行动作
            actions: [
              //第一个动作
              {
                //执行动作类型 设备输出、消息通知 此处为消息通知
                executor: "notifier",
                //配置
                configuration: {
                  //消息
                  message: {},
                  //通知方式
                  notifyType: "dingTalk",
                  //通知配置ID
                  notifierId: "1474225269423071232",
                  //模板ID
                  templateId: "1466703102988902400"
                }
              },
              //第二个动作
              {
                //执行动作类型 设备输出、消息通知 此处为设备输出
                executor: "device-message-sender",
                //配置
                configuration: {
                  //消息
                  message: {
                    //类型 属性、功能 此处为属性
                    messageType: "WRITE_PROPERTY",
                    properties: {
                      //属性KEY  属性值
                      A2: "设备输出属性值"
                    }
                  },

                  notifyType: "email",

                  //执行动作的设备ID
                  deviceId: "A1",
                  //执行动作设备的产品ID
                  productId: "0610_CSP111"
                }
              },
              //第三个执行动作
              {
                //执行动作类型 设备输出、消息通知 此处为设备输出
                executor: "device-message-sender",
                //配置
                configuration: {
                  //消息
                  message: {
                    //类型 属性、功能 此处为功能
                    messageType: "INVOKE_FUNCTION",
                    //功能ID
                    functionId: "StartRecord",
                    //功能参数属性值
                    inputs: [
                      {
                        name: "channel",
                        value: "1"
                      },
                      {
                        name: "streamId",
                        value: "2"
                      },
                      {
                        name: "endTime",
                        value: "3"
                      },
                      {
                        name: "name",
                        value: "4"
                      },
                      {
                        name: "downloadSpeed",
                        value: "5"
                      },
                      {
                        name: "local",
                        value: "true"
                      }
                    ]
                  },
                  //执行操作的设备ID
                  deviceId: "34020000000010000157",
                  //执行操作设备的产品ID
                  productId: "gb28181_device"
                }
              }
            ],
            //防抖
            shakeLimit: {
              //防抖是否开启
              enabled: true,
              //指定时长
              time: 426,
              //指定时长内抖动次数
              threshold: 624,
              //是否已触发
              alarmFirst: false
            }
          },
          //状态
          state: {
            text: "已停止",
            value: "stopped"
          },
          //创建时间
          createTime: 1674954792004
        },
        // 表单校验
        rules: {
          name: [
            {required: true, message: "请输入告警名称", trigger: "blur"}
          ]
        },
      }
    },
    methods: {
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          name: null,
          target: null,
          targetId: null,
          alarmRule: {
            name: null,
            deviceId: null,
            deviceName: null,
            triggers: [],
            actions: [],
            properties: [],
            productId: null,
            productName: null,
            shakeLimit: {
              enabled: false,
              time: null,
              threshold: null
            }
          }
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        getProduct(this.deviceDetailInfo.productId).then(response=>{
          let metadata = response.data.metadata;
          if (metadata){
            this.deriveMetadata = JSON.parse(metadata)
          }else {
            this.deriveMetadata = {
              events:[],
              functions:[],
              properties:[],
              tags:[]
            }
          }
        })
        this.reset();
        this.queryParams.publishState = 1;
        queryDevice(this.queryParams).then(response => {
          this.deviceList = response.data;
        });
        this.type = 1;
        this.open = true;
        this.title = "添加告警设置";
      },
      /** 修改按钮操作 */
      handleUpdate(id) {
        this.reset();
        this.type = 0;
        getDevice(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改告警设置";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.type === 0) {
              updateDevice(this.form).then(() => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
              });
            } else {
              this.form.configuration = JSON.stringify(this.form.configuration);
              addDevice(this.form).then(() => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
              });
            }
          }
        });
      },
      //执行操作集合新增
      addAlarmActions() {
        this.form.alarmRule.actions.push({
          configuration: {
            message: {
              messageType: null,
              properties: {},
              inputs: [],
            },
            deviceId: undefined,
            properties1: undefined,
            notifyType: undefined,
            notifierId: undefined,
            templateId: undefined,
            properties2: undefined,
            productId: undefined,
          }
        });
      },
      //执行操作集合删除
      removeAlarmActions(index) {
        this.form.alarmRule.actions.splice(index, 1);
      },
      //转换集合新增
      addAlarmTransition() {
        this.form.alarmRule.properties.push({});
      },
      //转换集合删除
      removeAlarmTransition(index) {
        this.form.alarmRule.properties.splice(index, 1);
      },
      //触发器集合新增
      addAlarmTriggers() {
        this.form.alarmRule.triggers.push({
          trigger: null,
          type: null,
          filters: [
            {
              key: null,
              value: null,
              operator: null
            }
          ]

        });
      },
      //触发器集合删除
      removeAlarmTriggers(index) {
        this.form.alarmRule.triggers.splice(index, 1);
      },
      //条件集合新增
      addAlarmFilters(i) {
        var trigger1 = this.form.alarmRule.triggers[i];
        if (trigger1 !== undefined) {
          trigger1.filters.push({});
        } else {
          trigger1 = {
            //触发器类型 设备触发、定时触发 此处为设备触发
            trigger: null,
            //类型：书简、属性、上线、下线 此处为上线
            type: null,
            //条件集合
            filters: [{
              key: null,
              value: null,
              operator: null
            }]
          }
        }
        this.form.alarmRule.triggers[i] = (trigger1)
      },
      //条件集合删除
      removeAlarmFilters(i, i1) {
        var trigger = this.form.alarmRule.triggers[i];
        trigger.filters.splice(i1, 1);
        this.form.alarmRule.triggers[i] = trigger
      },
      emptyAction(i){
        this.form.alarmRule.actions[i].configuration = {
          message: {
            messageType: null,
            properties: {},
          },
          deviceId: undefined,
          properties1: undefined,
          notifyType: undefined,
          notifierId: undefined,
          templateId: undefined,
          properties2: undefined,
          productId: undefined,

        }
      },
      queryPropertyOrFunctionlList(row){
        getDevice(row.deviceId).then(response => {
          getProduct(response.data.productId).then(res => {
            let data = res.data;
            var parse = JSON.parse(data.metadata);
            this.functionlList = parse.functions;
            this.propertylList = parse.properties;
          })
        })
      },
      queryNotifyConfigList(row){
        this.queryParams.type = row.notifyType;
        queryConfig(this.queryParams).then(response =>{
          this.notifyConfigList = response.rows;
        });
        this.queryParams.type = null;
      },
      queryNotifyTemplateList(row){
        this.queryParams.type = row.notifyType;
        queryTemplate(this.queryParams).then(response =>{
          this.notifyTemplateList = response.rows;
        });
        this.queryParams.type = null;
      },
    }
  };
</script>

<style lang="scss" scoped>
  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }

  // 设备状态
  .cron {
    width: 220px;
    margin-left: 10px;
  }

</style>
